'use strict'

class smart {
  constructor() {
    this.param = '/'
  }

  async get(c) {
    let ret = await c.service.psql.query(`select * from smart order by smart_id asc`)
    c.status(200).send(ret.rows)
  }

  async post(c) {
    var obj = c.body
    console.log(obj)
    if (obj) {
      var { smart_content, smart_tag } = obj
      let row = await c.service.psql.query(`select * from smart order by smart_id asc`)
      let smart_id = parseInt(row.rows[row.rows.length - 1].smart_id) + 1
      console.log(smart_id, smart_tag, smart_content)
      let ret = await c.service.psql.query(`insert into smart values('${smart_id}', '${smart_content}', '${smart_tag}')`)
      console.log(ret)
      c.status(200).send('已接收')
    } else {
      c.status(400).send('please check your data :)')
    }
  }

  async delete(c) {
    console.log(c)
    if (!c.body.isRows) {
      var id = c.body.id
      console.log(id)
      if (id) {
        let ret = await c.service.psql.query(`delete from smart where smart_id like '${id}'`)
        console.log(ret)
        c.send('已删除')

      } else {
        c.send('删除失败')
      }
    } else {
      var idArr = c.body.idArr
      console.log(idArr)
      for (let i = 0; i < idArr.length; i++) {
        let ret = await c.service.psql.query(`delete from smart where smart_id like '${idArr[i]}'`)
        console.log(ret)
      }
      c.send('complete')
    }
  }

  async put(c) {
    var req = c.body
    console.log(req)
    if (req.smart_content) {
      let ret = await c.service.psql.query(`update smart set smart_content = '${req.smart_content}' where smart_id like '${req.smart_id}'`)
      console.log('content', ret)
    }
    if (req.smart_tag) {
      let ret = await c.service.psql.query(`update smart set smart_tag = '${req.smart_tag}' where smart_id like '${req.smart_id}'`)
      console.log('tag', ret)
    }
    c.send('complete')
  }
}

module.exports = smart
